var templateParams = {
    tableTheads:["计划名称", "用例集", "执行机/组", "并发", "执行配置","执行时间", "任务状态", "创建时间"
        , "创建人", "修改时间", "修改人","备注", "操作"],
    btnTools:[{
        type:"primary",
        size:"M",
        id:"add-object",
        iconFont:"&#xe600;",
        name:"添加计划"
    },{
        type:"danger",
        size:"M",
        id:"batch-op",
        iconFont:"&#xe6bf;",
        name:"批量操作"
    }],
    formControls:[{
        edit:true,
        label:"ID",
        objText:"idText",
        input:[{
            hidden:true,
            name:"id"
        }]
        },
        {
            required:true,
            label:"计划名称",
            input:[{
                name:"plan_name"
            }]
        },
        {
            required:true,
            label:"是否并发执行",
            select:[{
                name:"parallel",
                option:[
                    {text: "是", value: "1"},
                    {text: "否", value: "0"}
                ]
            }]
        },
        {
            // required:true,
            label:"执行时间Cron表达式",
            input:[{
                name:"cron_express",
                value: ""
            }]
        },
        {
            label:"执行机组",
            objText:"executor_group_nameText",
            input:[{
                name:"executor_group_id",
                hidden:true
            }],
            button:[{
                style:"success",
                value:"选择",
                name:"choose-executor-group"
            },{
                style:"danger",
                value:"清除",
                name:"clear-executor-group"
            }]
        },
        {
            label:"执行机",
            objText: "executor_nameText",
            input:[{
                name:"executor_id",
                hidden:true
            }],
            button:[{
                style:"success",
                value:"选择",
                name:"choose-executor-slave"
            },{
                style:"danger",
                value:"清除",
                name:"clear-executor-slave"
            }]
        },
        {
            label:"测试配置",
            input:[{
                name:"exec_config_plan",
                hidden: true
            }],
            button:[{
                style:"primary",
                value:"配置",
                name:"setting-exec-config"
            }]
        },
        {
            label:"测试数据",
            input:[{
                name:"testdata_plan",
                hidden: true
            }],
            button:[{
                style:"primary",
                value:"配置",
                name:"setting-test-data"
            }]
        },
        {
            required:true,
            label:"过期时间(秒)",
            input:[{
                name:"expire_time",
                value: '999999999'
            }]
        },
        {
            required:true,
            label:"任务状态",
            select:[{
                name:"status",
                option:function(){
                    let options = [];
                    $.each(GLOBAL_PARAM.TEST_PLAN_STATUS, function(k, v) {
                        options.push({
                            text: v,
                            value: k
                        });
                    });

                    return options;
                }()
            }]
        },
        {
            edit:true,
            label:"创建时间",
            objText: "create_timeText"
        },
        {
            label:"备注",
            textarea:[{
                name:"mark"
            }]
        }
    ]};

var columnsSetting = [
    {
        "data":null,
        "render":function(data, type, full, meta){
            return checkboxHmtl(data.plan_name, data.id, "selectPlan");
        }},
    {"data": "id"},
    {
        "data":"plan_name",
        "width":"15%",
    },
    {
        "data":"testset_num",
        "render":function(data, type, full, meta){
            var context =
                [{
                    type:"default",
                    size:"M",
                    markClass:"show-set-count",
                    name:data || 0
                }];
            return btnTextTemplate(context);
        }
    },
    {
        "data": null,
        "width":"10%",
        "render": function(data){
            return GLOBAL_UTILS.stringUtils.isNotBlank(data.executor_name)
                ? data.executor_name : data.executor_group_name;
        }
    },
    {
        "data": "parallel",
        "render": function(data){
            return GLOBAL_PARAM.CUSTOM_JUDGE_TYPE[data] || '';
        }
    },
    {
        "data":"testdata_plan",
        "render":function(data) {
            return btnTextTemplate([{
                type:"primary",
                size:"M",
                markClass:"setting-exec-config",
                name:"配置"
            }]);
        }
    },
    ellipsisData("cron_express"),
    // {
    //     "data": "over_time",
    //     "render": function(data){
    //         return GLOBAL_UTILS.stringUtils.isBlank(String(data)) ? '' : data + '秒';
    //     }
    // },
    // {
    //     "data": "expire_time",
    //     "render": function(data){
    //         return GLOBAL_UTILS.stringUtils.isBlank(String(data)) ? '' : data + '秒';
    //     }
    // },
    {
        "data": "status",
        "render": function(data) {
            return GLOBAL_PARAM.TEST_PLAN_STATUS[data] || data;
        }
    },
    ellipsisData("create_time"),
    ellipsisData("creator_name"),
    ellipsisData("last_alter_time"),
    ellipsisData("last_mender_name"),
    longTextData("mark", "plan_name", "备注信息"),
    {
        "data":null,
        "render":function(data, type, full, meta){
            var context = [{
                title:"执行",
                markClass:"object-execute",
                iconFont:"&#xe603;"
            },{
                title:"编辑",
                markClass:"object-edit",
                iconFont:"&#xe6df;"
            },{
                title:"删除",
                markClass:"object-del",
                iconFont:"&#xe6e2;"
            }];
            return btnIconTemplate(context);
        }
    }];

var eventList = {
    "#add-object":function(){
        publish.renderParams.editPage.modeFlag = 0;
        layer_show("添加测试计划", editHtml, editPageWidth, editPageHeight.add, 1);
        publish.init();
    },
    "#batch-op":function(){
        layer.confirm(
            '请选择你需要进行的批量操作:',
            {
                title:'批量操作',
                btn:['删除', '取消'],
                shadeClose:true,
            },function(index){
                layer.close(index);
                batchOp($(".selectPlan:checked"), REQUEST_URL.WEB_TEST_PLAN.delPlan, "删除", null, "id");
            },function(index){
                layer.close(index);
            });
    },
    ".object-edit":function(){
        let data = table.row( $(this).parents('tr') ).data();

        publish.renderParams.editPage.modeFlag = 1;
        publish.renderParams.editPage.objId = data.id;
        publish.renderParams.editPage.currentObj = data;
        layer_show("编辑测试计划信息", editHtml, editPageWidth, editPageHeight.edit, 1);
        publish.init();
    },
    ".object-del":function(){
        let data = table.row( $(this).parents('tr') ).data();

        opObj("确认要删除此测试计划吗？", REQUEST_URL.WEB_TEST_PLAN.delPlan, {id:data.id}, this, "删除成功!");
    },
    //选择执行机
    "#choose-executor-slave": function() {
        if (GLOBAL_UTILS.stringUtils.isNotBlank($("#executor_group_id").val())) {
            layer.msg('你已选择了指定的执行机组！', {time: 1600});
            return;
        }

        layer_show('选择执行机', 'chooseExecutorMachine.html?callback=chooseExecutorMachineCallback', null, null, 2);
    },
    //清除选择
    "#clear-executor-slave": function() {
        $("#executor_id").val('');
        $("#executor_nameText").text('');
    },
    //选择执行机组
    "#choose-executor-group": function() {
        if (GLOBAL_UTILS.stringUtils.isNotBlank($("#executor_id").val())) {
            layer.msg('你已选择了指定的执行机！', {time: 1600});
            return;
        }

        layer_show('选择执行机组', 'chooseExecutorGroup.html?callback=chooseExecutorGroupCallback', null, null, 2);
    },
    //清除选择
    "#clear-executor-group": function() {
        $("#executor_group_id").val('');
        $("#executor_group_nameText").text('');
    },
    ".show-set-count": function(){
        let data = table.row( $(this).parents('tr') ).data();

        layer_show(data.plan_name + "-测试集管理", "webPlanSet.html" + "?plan_id=" + data.id, null, null, 2);
    },
    //执行测试
    ".object-execute":function() {
        let data = table.row( $(this).parents('tr') ).data();

        layer.confirm('确定执行该测试计划吗？', {icon: 0}, function(index){
            GLOBAL_UTILS.ajaxUtils.ajaxGet(REQUEST_URL.WEB_TEST_PLAN.execute + '&plan_id=' + data.id, function(d){
                layer.alert('开启执行成功,请到测试任务模块查询详情', {icon: 1});
            }, null, null, null, '正在开启中...');
            layer.close(index);
        });
    },
    //测试配置
    "#setting-exec-config":function(){
        let planExecConfig = $('#exec_config_plan').val();
        let config = {};
        if (!GLOBAL_UTILS.jsonUtils.isJsonStr(planExecConfig)) {
            config = {
                'browserName': 'chrome',
                'platformName': 'desktop',
                'appConfig': '{"platformName":"Android","platformVersion":"10","uuid":"","appPackage":"","appActivity":"","newCommandTimeout":360000,"noReset":"True"}',
                'findElementTimeout': 5,
                'pageLoadTimeout': 90
            };
        } else {
            config = JSON.parse(planExecConfig);
        }

        layer_show('测试计划执行配置', templates['test-plan-exec-config'](config), 670, 410, 1, function(layero, index){
            $(layero).find('#browserName').val(config['browserName']);
            $(layero).find('#platformName').val(config['platformName']);
            $(layero).find('#platformName').change(function(){
              let name = $(layero).find('#platformName').val();
              if (name === 'desktop') {
                $(layero).find('#appConfig').attr('disabled', 'disabled');
                $(layero).find('#browserName').removeAttr('disabled');
              } else {
                $(layero).find('#browserName').attr('disabled', 'disabled');
                $(layero).find('#appConfig').removeAttr('disabled');
              }
            });
        }, function(index, layero){
            config['browserName'] = $(layero).find('#browserName').val();
            config['findElementTimeout'] = $(layero).find('#findElementTimeout').val();
            config['pageLoadTimeout'] = $(layero).find('#pageLoadTimeout').val();
            config['platformName'] = $(layero).find('#platformName').val();
            config['appConfig'] = $(layero).find('#appConfig').val();

            $('#exec_config_plan').val(JSON.stringify(config));
            layer.close(index);
            layer.msg('已更新！', {icon: 1, time:1500});
        }, null, {shadeClose: false});
    },
    '#setting-test-data':function() {
        let data = $('#testdata_plan').val();
        if (GLOBAL_UTILS.stringUtils.isBlank(data)
            || !GLOBAL_UTILS.jsonUtils.isJsonStr(data)) {
            data = "{}";
        }

        layer_show('配置测试数据', templates['web-test-config-view']({default_data: JSON.parse(data)}), 580, 450, 1, function(layero, index){
            $(layero).find('#update-web-test-config').one('click', function(){  //更新配置
                let configObj = {};
                $("#web-test-config-variables").children('.row').each(function(i){
                    let key = $(this).find('input').eq(0).val();
                    let value = $(this).find('input').eq(1).val();
                    if (strIsNotEmpty(key) && strIsNotEmpty(value)) {
                        configObj[key] = value;
                    }
                });
                layer.close(index);
                $('#testdata_plan').val(JSON.stringify(configObj));
                layer.msg('配置成功！', {icon: 1, time: 1500});
            });
        }, null, null, {shadeClose:false});
    },
    '.setting-exec-config':function() {
        let data = table.row( $(this).parents('tr') ).data();
        let config;
        if (GLOBAL_UTILS.stringUtils.isBlank(data.exec_config_plan)
            || !GLOBAL_UTILS.jsonUtils.isJsonStr(data.exec_config_plan)) {
            data.exec_config_plan = "{}";
            config = {
              'browserName': 'chrome',
              'platformName': 'desktop',
              'appConfig': '{"platformName":"Android","platformVersion":"10","uuid":"","appPackage":"","appActivity":"","newCommandTimeout":360000,"noReset":"True"}',
              'findElementTimeout': 5,
              'pageLoadTimeout': 90
            };
        } else {
            config = JSON.parse(data.exec_config_plan);
        }

        layer_show('测试计划执行配置', templates['test-plan-exec-config'](config), 670, 410, 1, function(layero, index){
            $(layero).find('#platformName').change(function(){
              let name = $(layero).find('#platformName').val();
              if (name === 'desktop') {
                $(layero).find('#appConfig').attr('disabled', 'disabled');
                $(layero).find('#browserName').removeAttr('disabled');
              } else {
                $(layero).find('#browserName').attr('disabled', 'disabled');
                $(layero).find('#appConfig').removeAttr('disabled');
              }
            });
            $(layero).find('#browserName').val(config['browserName']);
            $(layero).find('#platformName').val(config['platformName']);
            $(layero).find('#platformName').trigger('change')
        }, function(index, layero){
            config['browserName'] = $(layero).find('#browserName').val();
            config['findElementTimeout'] = $(layero).find('#findElementTimeout').val();
            config['pageLoadTimeout'] = $(layero).find('#pageLoadTimeout').val();
            config['platformName'] = $(layero).find('#platformName').val();
            config['appConfig'] = $(layero).find('#appConfig').val();

            if (!CompareJsonObj(config, JSON.parse(data.exec_config_plan))) {
                GLOBAL_UTILS.ajaxUtils.ajaxPost(REQUEST_URL.WEB_TEST_PLAN.updateData, {id:data.id, exec_config_plan:JSON.stringify(config)}, function(json) {
                    layer.msg('更新成功!', {icon:1, time: 1500});
                    refreshTable();
                });
            } else {
                layer.msg('未有改动!', {icon:5, time:1800});
            }

            layer.close(index);
        }, null, {shadeClose: false, offset: '18px'});

    },
    "#web-test-config-add-variable":function(){//增加一对key-value
        $("#web-test-config-variables").append('<div class="row cl"><div class="form-label col-xs-5 col-sm-5">'
            + '<input type="text" class="input-text radius"></div>'
            + '<div class="formControls col-xs-5 col-sm-5"><input type="text" class="input-text radius"></div>'
            + '<div class="formControls col-xs-2 col-sm-2"><a class="btn btn-default radius">'
            + '<i class="Hui-iconfont">&#xe60b;</i></a></div></div>');
    },
    "#web-test-config-clear-all-varibale":function(){//清除全部
        layer.confirm('确认删除下列全部的测试数据吗？', {title:'警告'}, function(index){
            $("#web-test-config-variables").html('');
            layer.msg('全部删除成功!', {icon:1, time:1800});
            layer.close(index);
        });
    },
    "#web-test-config-variables a":function(){//删除该项
        var that = this;
        layer.confirm('确认删除该项测试数据吗?', {title:'警告'}, function(index) {
            $(that).parent('.formControls').parent('.row').remove();
            layer.msg('删除成功!', {icon:1, time:1800});
            layer.close(index);
        });
    }
};

var mySetting = {
    eventList:eventList,
    templateCallBack:function(df){
        df.resolve();
    },
    listPage:{
        listUrl:REQUEST_URL.WEB_TEST_PLAN.listPlan,
        tableObj:".table-sort",
        columnsSetting:columnsSetting,
        columnsJson:[0, 14],
        dtOtherSetting:{
            serverSide:false
        }
    },
    editPage:{
        editUrl:REQUEST_URL.WEB_TEST_PLAN.editPlan,
        getUrl:REQUEST_URL.WEB_TEST_PLAN.getPlan,
        rules:{
            plan_name:{
                required:true,
                minlength:2,
                maxlength:255
            },
            parallel: {
                required: true
            },
            // cron_express: {
            //     required: true
            // },
            over_time: {
                required: true,
                digits:true
            },
            expire_time: {
                required: true,
                digits:true
            }
        }
    },
    templateParams:templateParams
};

$(function(){
    publish.renderParams = $.extend(true,publish.renderParams,mySetting);
    publish.init();
});


function chooseExecutorGroupCallback (obj) {
    $('#executor_group_id').val(obj.id);
    $('#executor_group_nameText').text(obj.group_name);
}

function chooseExecutorMachineCallback (obj) {
    $('#executor_id').val(obj.id);
    $('#executor_nameText').text(obj.slave_name);
}
